<template>
  <div class="weather-view">
    <header class="home-header">
      <nav>
        <a href="/" @click="$router.push('/')">
          <div class="logo">
            <img src="../img/太阳.png" alt="logo" />
            <p>新中地天气</p>
          </div>
        </a>
        <div class="weather-info">
          <h4>{{ wuhanweather.city }}</h4>
          <span
            >实时天气：{{ wuhanweather.weather }}
            {{ wuhanweather.temperature }}℃</span
          >
          <span
            >{{ wuhanweather.winddirection }}风{{
              wuhanweather.windpower
            }}级</span
          >
        </div>
        <div class="weather-icon">
          <img src="../img/提示说明.png" alt="提示说明" @click="showTip" />
          <img
            v-if="isAddVisible"
            src="../img/加号.png"
            alt="加号"
            @click="handleadd"
          />
        </div>
        <div v-if="isTipVisible" class="tip-dialog">
          <div class="tip-content">
            <h3>关于:</h3>
            <span>这个应用可以用来追踪你选择城市的当前天气</span>
            <h3>如何使用:</h3>
            <div>1.点击搜索框输入你希望追踪的城市</div>
            <div>2.在搜索结果中选中一个城市，你将获取当地最新的天气</div>
            <div>3.点击右侧的＋号可以将追踪城市的天气情况保存在首页</div>
            <h3>移除城市:</h3>
            <div>如果你不想在首页关注某个城市,可以通过底部的按钮删除它</div>
            <button
              @click="closeTip"
              style="
                height: 30px;
                width: 80px;
                background-color: rgb(0, 102, 138);
                color: white;
                border: none;
                border-radius: 5px;
                margin-top: 20px;
              "
            >
              关闭
            </button>
          </div>
        </div>
      </nav>
    </header>
    <main class="w-main">
      <div class="w-title">
        你正在预览{{ weatherInfo.city }}的天气信息
        <span style="display: none">，可以通过右上角的"+"号按钮保存起来</span>
      </div>
      <div class="dynamic" v-if="weatherInfo">
        <h1>当日气温是: {{ weatherInfo.temperature }}摄氏度</h1>
        <h1>当日天气是：{{ weatherInfo.weather }}</h1>
        <h1>当日风向是：{{ weatherInfo.winddirection }}风</h1>
        <h1>当日风力是：{{ weatherInfo.windpower }}级</h1>
      </div>
      <hr class="w-hr" />
      <div class="divider-weather">
        <div class="weather-container">
          <div class="weather-item">
            <div
              class="weather-item-title"
              v-for="(weather, index) in weatherDown"
              :key="index"
            >
              <span>
                {{
                  index === 0
                    ? '今日'
                    : index === 1
                    ? '明天'
                    : `周${getDayLabel(weather)}`
                }}
              </span>
              <span>{{ formatDate(weather) }}</span>
              <span>{{ weather.dayweather }}</span>
              <span>风力 {{ weather.daypower }}级</span>
            </div>
          </div>
          <div class="weathercanvas">
            <v-chart :option="weatherOption" ></v-chart>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, watch,computed } from 'vue'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
import { useWeatherStore } from '../stores/weather'
const weatherOption = ref({})
const router = useRouter()
const route = useRoute()
const isAddVisible = ref(false) // 控制右侧的加号按钮的显示
const isTipVisible = ref(false) // 控制提示栏的显示false,
const wuhanweather = ref({})
const weatherStore = useWeatherStore()
const fromPath = ref(route.query.from || '')
const citys = ref(route.query.city || '')
const values = ref(route.query.value || '')
const temperature = ref(null)

const showTip = () => {
  isTipVisible.value = true // 显示提示栏
}
const closeTip = () => {
  isTipVisible.value = false // 隐藏提示栏
}
const handleadd = () => {
  weatherStore.addWeatherData({
    city: citys.value,
    temperature: temperature.value,
    value: values.value,
    path: fromPath.value,
  })
  router.push({ path: '/' })
}

const renderLineChart = (chartOption, data1, data2) => {
  chartOption.value = {
    xAxis: {
      type: 'category',
      show: true,
      axisLabel: {
        show: false, // 隐藏标签
      },
    },
    yAxis: {
      type: 'value',
      show: false,
    },

    series: [
      {
        data: data1,
        type: 'line',
        smooth: true,
        label: {
          show: true,
          position: 'top',
        },
      },
      {
        data: data2,
        type: 'line',
        smooth: true,
        label: {
          show: true,
          position: 'top',
        },
      },
    ],
  }
}

const formatDate = (data) => {
  return data.date.slice(6, 10) || '未知' // 返回处理后的日期
}

const getDayLabel = (data) => {
  const weekMap = {
    1: '一',
    2: '二',
    3: '三',
    4: '四',
    5: '五',
    6: '六',
    7: '日',
  }
  return weekMap[data.week] || '未知' // 返回对应的星期几或 '未知'
}
// 定义响应式数据
const weatherInfo = ref({
  city: '',
  weather: '',
  temperature: '',
  winddirection: '',
  windpower: '',
})
const weatherDown = ref([
  {
    date: '',
    week: '',
    dayweather: '',
    daywind: '',
    daypower: '',
    daytemp_float: '',
    nighttemp_float: '',
  },
])

// 获取天气信息的函数
const fetchWeather = async () => {
  try {
    const response = await axios.get(
      'https://restapi.amap.com/v3/weather/weatherInfo',
      {
        params: {
          city: values.value,
          key: 'b3c72769ff1bcbdd3d94dca1bff9651c',
          extensions: 'base',
        },
      }
    )
    const wuhan = await axios.get(
      'https://restapi.amap.com/v3/weather/weatherInfo',
      {
        params: {
          city: '420100',
          key: 'b3c72769ff1bcbdd3d94dca1bff9651c',
          extensions: 'base',
        },
      }
    )
    const realdown = await axios.get(
      'https://restapi.amap.com/v3/weather/weatherInfo',
      {
        params: {
          city: values.value,
          key: 'b3c72769ff1bcbdd3d94dca1bff9651c',
          extensions: 'all',
        },
      }
    )
    const data = response.data.lives[0]
    const data2 = realdown.data.forecasts[0].casts
    const wuhanData = wuhan.data.lives[0]
    wuhanweather.value = wuhanData
    weatherInfo.value = {
      city: data.city,
      weather: data.weather,
      temperature: data.temperature,
      winddirection: data.winddirection,
      windpower: data.windpower,
    }
    weatherDown.value = data2.map((item) => ({
      date: item.date,
      week: item.week,
      dayweather: item.dayweather,
      daywind: item.daywind,
      daypower: item.daypower,
      daytemp_float: item.daytemp_float,
      nighttemp_float: item.nighttemp_float,
    }))
    const dayTemps = weatherDown.value.map((item) => item.daytemp_float)
    const nightTemps = weatherDown.value.map((item) => item.nighttemp_float)
    renderLineChart(weatherOption, dayTemps, nightTemps)
    temperature.value = data.temperature
    /* return temperature */
  } catch (error) {
    console.error('获取天气信息失败:', error)
  }
}
// 使用 computed 定义 from
try {
const xx = computed(() => route.query.xx);
console.log(xx.value)
// 监听 from 的变化
watch(xx, (newFrom) => {
  console.log(newFrom);
  if (newFrom === 'header') {
    isAddVisible.value = true; // 从 todoheader 进入时 显示加号
  } else if (newFrom === 'item') {
    isAddVisible.value = false; // 如果是通过 todoitem 进入 WeatherView，则设置加号为隐藏
  } else {
    isAddVisible.value = false; // 其他情况可以默认不显示
  }
},
{ immediate: true }
);} catch (error) {
  console.error('获取 from 失败:', error)
}
// 在组件挂载时调用 fetchWeather
onMounted(() => {
  fetchWeather()
})
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
.weather-view {
  min-height: 100vh;
  flex-direction: column;
  display: flex;
  background-color: rgb(0, 102, 138);
}
.home-header {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  height: 80px;
  position: sticky;
  top: 0px;
  nav {
    display: flex;
    color: white;
    height: 80px;
    gap: 1rem;
    align-items: center;
    max-width: 1024px;
    margin: auto;
    padding: 0 5rem;
    .tip-dialog {
      position: fixed;
      top: -400px;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-self: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0); /* 半透明背景 */
      z-index: 100; /* 确保在其他元素之上 */
      .tip-content {
      background: white;
      padding: 20px;
      color: black;
      border-radius: 5px;
      text-align: left;
    }
    }

  
    a {
      color: inherit;
      text-decoration: none;
      .logo {
        gap: 0.75rem;
        display: flex;
        align-items: center;
        img {
          width: 24px;
          height: 24px;
        }
        p {
          font-size: 1.5rem;
          line-height: 2rem;
          font-weight: 900;
        }
      }
    }
    .weather-info {
      display: flex;
      align-items: center;
      gap: 1rem;
      h4 {
        font-size: 1.125rem;
        line-height: 1.75rem;
        margin: 0;
      }
      span {
        font-size: 0.875rem;
        line-height: 1.25rem;
      }
    }
    .weather-icon {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      img {
        width: 24px;
        height: 24px;
        cursor: pointer;
      }
    }
  }
}
.w-main {
  color: white;
  .w-title {
    text-align: center;
    background: rgb(0, 78, 113);
    padding: 0.5rem;
  }
  .dynamic {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 1.5rem;
    h1 {
      font-size: inherit;
      font-weight: inherit;
      margin: 0;
    }
  }
  .w-hr {
    margin-top: 1.5rem;
    border-bottom: 2px solid rgba(255, 255, 255, 0.01);
    height: 0;
  }
}
.divider-weather {
  max-width: 768px;
  margin: auto;
  padding: 0 10rem;
  .weather-container {
    padding: 2.5rem 3rem;
    background: rgb(0, 78, 113);
    border-radius: 0.25rem;
    margin-top: 0.5rem;
    color: white;
    .weather-item {
      display: flex;
      gap: 1.5rem;
      .weather-item-title {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
      }
    }
    .weathercanvas {
      height: 20rem;
      width: 100%;
      margin-top: 2.5rem;
      z-index: 1;
    }
  }
}
</style>
